// Package drivers redis db drives
package drivers

import (
	"encoding/json"
	"ginmin/configs"
	"github.com/gomodule/redigo/redis"
	"github.com/tidwall/gjson"
	"log"
	"strconv"
	"time"
)

var RedisDb *redis.Pool // db pool instance

func init() {
	RdsConfig := configs.GetRedisConfig()
	if RdsConfig["RDS_SERVER"] != "" {
		RedisDb = NewRedisStore(
			10,
			RdsConfig["RDS_NETWORK"],
			RdsConfig["RDS_SERVER"],
			RdsConfig["RDS_PWD"],
			RdsConfig["RDS_DB"],
		)
	}
}

// Serializer
// @Description: 序列化
// @param value
// @return []byte
func Serializer(value interface{}) []byte {
	mjson, _ := json.Marshal(map[string]interface{}{
		"jsondata": value,
	})
	return mjson
}

// Deserializer
// @Description: 反序列化
// @param value
// @return interface{}
func Deserializer(value []byte) interface{} {
	strs := gjson.Parse(string(value)).Value().(map[string]interface{})
	if len(strs) > 0 {
		return strs["jsondata"]
	}
	return nil
}

// NewRedisStore 创建新的redis存储
func NewRedisStore(size int, network, address, password, database string) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     size,
		IdleTimeout: 240 * time.Second,
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
		Dial: func() (redis.Conn, error) {
			db, err := strconv.Atoi(database)
			if err != nil {
				return nil, err
			}

			c, err := redis.Dial(
				network,
				address,
				redis.DialDatabase(db),
				redis.DialPassword(password),
			)
			if err != nil {
				log.Println("无法创建Redis连接：%s", err)
				return nil, err
			}
			return c, nil
		},
	}
}
